package com.poposchool.project.controller;

import com.poposchool.project.common.Result;
import com.poposchool.project.entity.Role;
import com.poposchool.project.service.RoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Wang Jie
 * @Date 2022/7/4 16:24
 * @Version 1.0
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Resource
    RoleService roleService;

    @GetMapping("/roleCounts")
    public Result getCounts() {
        return Result.success(roleService.getAllNum());
    }


    @GetMapping("/roles")
    public List<Role> getRoles() {
        return roleService.getRoles();
    }

    @GetMapping("/role")
    public Role getRole(Integer id) {
        return roleService.getRoleById(id);
    }

    @PostMapping("/save")
//    如果参数什么都不加，那么就是path中传来的
    public void saveRole(@RequestBody Role role) {
        roleService.insertRole(role);
    }

    @PostMapping("/update")
//    @RequestParam("user")必须指定要有user这个key
    public void updateRole(@RequestBody Role role) {
        roleService.updateRole(role);
    }

    @GetMapping("/pageRoles")
    public Map<String, Object> getPage(
            @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", defaultValue = "6") Integer pageSize,
            @RequestParam(name = "name", defaultValue = "") String name) {
        Map<String, Object> map = new HashMap<>();
//      放入总数量
        map.put("total", roleService.getAllNum());
//      多条件查询
        map.put("roles", roleService.getPageRoles(pageNum, pageSize, name));
        return map;
    }

    @DeleteMapping("/deleteRole")
    public void deleteUser(Integer id) {
        roleService.deleteRole(id);
    }


    @PostMapping("/batchDeleteRoles")
//    参数类型不对，@RequestBody 后面用Map或者是javabean
    public void batchDeleteUsers(@RequestBody Map<String, List<Integer>> ids) {
        if (ids.get("ids").size() == 0) {
            return;
        }
        roleService.batchDeleteRoles(ids.get("ids"));
    }

    //   绑定角色和菜单的关系 List<Integer> menuIds
    @PostMapping("/roleMenu/{roleId}")
    public Result setRoleMenu(@PathVariable Integer roleId, @RequestBody Map<String, List<Integer>> map) {
        if (roleId != null && map != null) {
            //先把原来的都删除了，再覆盖上去
            roleService.deleteRoleMenuById(roleId);
            roleService.roleMenu(roleId, map.get("menuIds"));
        }
        return Result.success();
    }

    //   更加roleId获取映射menuId
    @GetMapping("/roleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId) {
        if (roleId != null) {
            return Result.success(roleService.getRoleMenu(roleId));
        }
        return Result.success();
    }
}
